<template>
  <a-card :bordered="false">
    <a-spin :spinning="loading">
      <a-row :gutter="20">
        <a-col :span="11" v-for="(item, index) in dataSourse" :key="index">
          <a-card
            :title="item.type == 'merchant' ? '全部商户概况' : item.type == 'merchantOrder' ? '商户订单状态' : ''"
            :hoverable="true"
            style="margin-bottom: 30px"
          >
            <a-row :gutter="80">
              <a-col :span="8">
                <a-card
                  title=""
                  :hoverable="true"
                  style="background-color: #fafafa"
                  :head-style="{ textAlign: 'center' }"
                  :body-style="{ textAlign: 'center', fontWeight: 'bold', padding: '10px' }"
                >
                  <span style="font-size: 20px; line-height: 50px">
                    {{
                      item.type == 'allOrder'
                        ? '订单销量'
                        : item.type == 'site'
                        ? item.name + '站点销量'
                        : item.type == 'merchant'
                        ? '全部商户'
                        : item.type == 'merchantOrder'
                        ? '未接单'
                        : ''
                    }}
                  </span>
                  <span style="font-size: 30px; line-height: 50px; margin-left: 5px">{{ item.total1 }}</span>
                </a-card>
              </a-col>
              <a-col :span="8">
                <a-card
                  title=""
                  :hoverable="true"
                  style="background-color: #fafafa"
                  :head-style="{ textAlign: 'center' }"
                  :body-style="{ textAlign: 'center', fontWeight: 'bold', padding: '10px' }"
                >
                  <span style="font-size: 20px; line-height: 50px">{{
                    item.type == 'allOrder'
                      ? '营业总额'
                      : item.type == 'site'
                      ? item.name + '站点营业总额'
                      : item.type == 'merchant'
                      ? '营业中'
                      : item.type == 'merchantOrder'
                      ? '出餐中'
                      : ''
                  }}</span>
                  <span style="font-size: 30px; line-height: 50px; margin-left: 5px"
                    >{{ item.total2 }} {{ item.type == 'allOrder' || item.type == 'site' ? '¥' : '' }}</span
                  >
                </a-card>
              </a-col>
              <a-col :span="8">
                <a-card
                  title=""
                  :hoverable="true"
                  style="background-color: #fafafa"
                  :head-style="{ textAlign: 'center' }"
                  :body-style="{ textAlign: 'center', fontWeight: 'bold', padding: '10px' }"
                >
                  <span style="font-size: 20px; line-height: 50px">{{
                    item.type == 'allOrder'
                      ? '营业利润'
                      : item.type == 'site'
                      ? item.name + '站点营业利润'
                      : item.type == 'merchant'
                      ? '打烊中'
                      : item.type == 'merchantOrder'
                      ? '已出餐'
                      : ''
                  }}</span>
                  <span style="font-size: 30px; line-height: 50px; margin-left: 5px"
                    >{{ item.total3 }} {{ item.type == 'allOrder' || item.type == 'site' ? '¥' : '' }}</span
                  >
                </a-card>
              </a-col>
            </a-row>
          </a-card>
        </a-col>
      </a-row>
    </a-spin>
    <!-- 查询区域 -->
    <div class="table-page-search-wrapper">
      <a-form layout="inline" @keyup.enter.native="searchQuery">
        <a-row :gutter="24">
          <a-col :span="5">
            <a-form-model-item label="门店名称">
              <a-input v-model="queryParam.storeName" />
            </a-form-model-item>
          </a-col>
          <a-col :span="5">
            <a-form-model-item label="门店名称">
              <a-select :allowClear="true" v-model="queryParam.storeName" @change="storeChange">
                <a-select-option
                  v-for="(item, index) in storeList"
                  :key="index"
                  :value="item.id"
                  @click="clickInfo(item)"
                  >{{ item.storeName }}</a-select-option
                >
              </a-select>
            </a-form-model-item>
          </a-col>

          <a-col :span="5">
            <a-form-model-item label="营业状态">
              <a-select v-model="queryParam.businessState" :allowClear="true" @change="searchQuery">
                <a-select-option value="YES">营业</a-select-option>
                <a-select-option value="NO">打烊</a-select-option>
              </a-select>
            </a-form-model-item>
          </a-col>
          <a-col :span="5">
            <a-form-model-item label="站点">
              <j-dict-select-tag
                v-model="queryParam.siteId"
                dict-code="HC_SITE,NAME,ID"
                placeholder="请选择站点"
                @change=""
              />
            </a-form-model-item>
          </a-col>
          <a-col :span="5">
            <a-form-model-item label="商家接单状态">
              <a-select v-model="queryParam.storeStatus" :allowClear="true" @change="searchQuery">
                <a-select-option value="NO">未接单</a-select-option>
                <a-select-option value="YES">已出餐</a-select-option>
                <a-select-option value="WAIT">出餐中</a-select-option>
              </a-select>
            </a-form-model-item>
          </a-col>
          <a-col :span="4">
            <span style="float: left; overflow: hidden" class="table-page-search-submitButtons">
              <a-button type="primary" @click="searchQuery" icon="search">查询</a-button>
              <a-button type="primary" @click="searchReset" icon="reload" style="margin-left: 8px">重置</a-button>
            </span>
          </a-col>
        </a-row>
      </a-form>
    </div>
    <!-- 查询区域-END -->

    <!-- 操作按钮区域 -->
    <div class="table-operator">
      <a-button @click="handleAdd" type="primary" icon="plus">新增</a-button>
      <!--      <a-button type="primary" icon="download" @click="handleExportXls('商户')">导出</a-button>-->
      <!--      <a-upload name="file" :showUploadList="false" :multiple="false" :headers="tokenHeader" :action="importExcelUrl" @change="handleImportExcel">-->
      <!--        <a-button type="primary" icon="import">导入</a-button>-->
      <!--      </a-upload>-->
      <!-- 高级查询区域 -->
      <!--      <j-super-query :fieldList="superFieldList" ref="superQueryModal" @handleSuperQuery="handleSuperQuery"></j-super-query>-->
      <a-dropdown v-if="selectedRowKeys.length > 0">
        <a-menu slot="overlay">
          <!--          <a-menu-item key="1" @click="batchDel">-->
          <!--            <a-icon type="delete"/>-->
          <!--            删除-->
          <!--          </a-menu-item>-->
          <a-menu-item key="3" @click="editStateBatch(0)"> 营业</a-menu-item>
          <a-menu-item key="4" @click="editStateBatch(2)"> 打烊</a-menu-item>
        </a-menu>
        <a-button style="margin-left: 8px">
          批量操作
          <a-icon type="down" />
        </a-button>
      </a-dropdown>
    </div>

    <!-- table区域-begin -->
    <div>
      <div class="ant-alert ant-alert-info" style="margin-bottom: 16px">
        <i class="anticon anticon-info-circle ant-alert-icon"></i> 已选择
        <a style="font-weight: 600">{{ selectedRowKeys.length }}</a
        >项
        <a style="margin-left: 24px" @click="onClearSelected">清空</a>
      </div>

      <a-table
        ref="table"
        size="middle"
        :scroll="{ x: true }"
        :bordered="false"
        rowKey="id"
        :columns="columns"
        :dataSource="dataSource"
        :pagination="ipagination"
        :rowSelection="{ selectedRowKeys: selectedRowKeys, onChange: onSelectChange }"
        :loading="loading"
        class="j-table-force-nowrap"
        @change="handleTableChange"
      >
        <template slot="businessHoursSlot" slot-scope="text, record, index">
          <a-row v-for="item in JSON.parse(text)">
            <span v-if="item.startTime && item.endTime">{{ item.startTime + ' - ' + item.endTime }}</span>
          </a-row>
        </template>
        <template slot="stateSlot" slot-scope="text, record, index">
          <a-switch
            :loading="record.stateLoading"
            checked-children="营业"
            un-checked-children="打烊"
            :checked="record.businessState == '营业' ? true : false"
            @click="stateEdit(record, index)"
          />
        </template>

        <template slot="htmlSlot" slot-scope="text">
          <div v-html="text"></div>
        </template>
        <template slot="imgSlot" slot-scope="text, record">
          <span v-if="!text" style="font-size: 12px; font-style: italic">无图片</span>
          <img
            v-else
            :src="getImgView(text)"
            :preview="record.id"
            height="25px"
            alt=""
            style="max-width: 80px; font-size: 12px; font-style: italic"
          />
        </template>
        <template slot="fileSlot" slot-scope="text">
          <span v-if="!text" style="font-size: 12px; font-style: italic">无文件</span>
          <a-button v-else :ghost="true" type="primary" icon="download" size="small" @click="downloadFile(text)">
            下载
          </a-button>
        </template>

        <span slot="action" slot-scope="text, record">
          <a @click="handleEdit(record)">编辑</a>
          <a-divider type="vertical" />
          <a @click="handleCopy(record)">复制</a>
          <a-divider type="vertical" />
          <a @click="getTokenById(record)">管理</a>
          <a-divider type="vertical" />
          <a-popconfirm title="确定删除吗?" @confirm="() => handleDelete(record.id)">
            <a>删除</a>
          </a-popconfirm>

          <!--          <a-divider type="vertical" />-->
          <!--          <a-dropdown>-->
          <!--            <a class="ant-dropdown-link">更多 <a-icon type="down" /></a>-->
          <!--            <a-menu slot="overlay">-->
          <!--              <a-menu-item>-->
          <!--                <a @click="handleDetail(record)">详情</a>-->
          <!--              </a-menu-item>-->
          <!--              <a-menu-item>-->
          <!--                <a-popconfirm title="确定删除吗?" @confirm="() => handleDelete(record.id)">-->
          <!--                  <a>删除</a>-->
          <!--                </a-popconfirm>-->
          <!--              </a-menu-item>-->
          <!--            </a-menu>-->
          <!--          </a-dropdown>-->
        </span>
      </a-table>
    </div>

    <hc-merchant-modal ref="modalForm" @ok="modalFormOk"></hc-merchant-modal>
    <hc-merchant-modal-copy-this ref="modalFormCopyThis" ></hc-merchant-modal-copy-this>
  </a-card>
</template>

<script>
import '@/assets/less/TableExpand.less'
import { mixinDevice } from '@/utils/mixin'
import { JeecgListMixin } from '@/mixins/JeecgListMixin'
import HcMerchantModal from './modules/HcMerchantModal'
import HcMerchantModalCopyThis from './modules/HcMerchantModalCopyThis'
import { postAction, getAction } from '@/api/manage'

export default {
  name: 'HcMerchantList',
  mixins: [JeecgListMixin, mixinDevice],
  components: {
    HcMerchantModal,
    HcMerchantModalCopyThis,
  },
  data() {
    return {
      description: '商户管理页面',
      // 表头
      columns: [
        {
          title: '#',
          dataIndex: '',
          key: 'rowIndex',
          width: 60,
          align: 'center',
          customRender: function (t, r, index) {
            return parseInt(index) + 1
          },
        },
        {
          title: '排序',
          align: 'center',
          dataIndex: 'sort',
        },
        // {
        //   title: '门店Logo',
        //   align: "center",
        //   dataIndex: 'logo',
        //   scopedSlots: {customRender: 'imgSlot'}
        // },
        // {
        //   title: '门店登录账号',
        //   align: "center",
        //   dataIndex: 'loginAccount'
        // },
        {
          title: '站点名称',
          align: 'center',
          dataIndex: 'siteName',
        },
        {
          title: '门店名称',
          align: 'center',
          dataIndex: 'storeName',
        },
        // {
        //   title: '门店描述',
        //   align: "center",
        //   dataIndex: 'storeDescription'
        // },
        {
          title: '门店菜品合作单价',
          align: 'center',
          dataIndex: 'storeUnitPrice',
          customRender: function (t, r, index) {
            if(t){
              let parse = JSON.parse(t)
              return parse.join(',')
            }else{
              return ''
            }
          },
        },
        // {
        //   title: '开启自定义价格',
        //   align: "center",
        //   dataIndex: 'customPriceFlag'
        // },
        {
          title: '门店营业时间',
          align: 'center',
          dataIndex: 'businessHours',
          scopedSlots: { customRender: 'businessHoursSlot' },
        },
        // {
        //   title: '门店下午营业时间',
        //   align: 'center',
        //   dataIndex: 'afternoonHoursEnd',
        //   customRender: function (t, r, index) {
        //     return r.afternoonHoursBegin + ' - ' + r.afternoonHoursEnd
        //   },
        // },
        // {
        //   title: '门店资质',
        //   align: "center",
        //   dataIndex: 'qualifications',
        //   scopedSlots: {customRender: 'imgSlot'}
        // },
        {
          title: '营业状态',
          align: 'center',
          dataIndex: 'businessState',
          scopedSlots: { customRender: 'stateSlot' },
        },
        {
          title: '商家接单状态',
          align: 'center',
          dataIndex: 'storeStatus',
        },
        {
          title: '包装评分',
          align: 'center',
          dataIndex: 'packagingScore',
        },
        {
          title: '份量评分',
          align: 'center',
          dataIndex: 'componentScore',
        },
        {
          title: '口味评分',
          align: 'center',
          dataIndex: 'flavorScore',
        },
        // {
        //   title: '上架状态',
        //   align: "center",
        //   dataIndex: 'state',
        //   scopedSlots: {customRender: 'stateSlot'}
        // },
        {
          title: '操作',
          dataIndex: 'action',
          align: 'center',
          fixed: 'right',
          width: 147,
          scopedSlots: { customRender: 'action' },
        },
      ],
      url: {
        list: '/hc/hcMerchant/list',
        merchantList: '/hc/hcMerchant/merchantList',
        delete: '/hc/hcMerchant/delete',
        deleteBatch: '/hc/hcMerchant/deleteBatch',
        exportXlsUrl: '/hc/hcOrderMerchant/exportXls',
        importExcelUrl: 'hc/hcMerchant/importExcel',
      },
      dictOptions: {},
      superFieldList: [],
      dataSourse: [],
      storeList: [],
    }
  },
  created() {
    this.getSuperFieldList()
  },
  computed: {
    importExcelUrl: function () {
      return `${window._CONFIG['domianURL']}/${this.url.importExcelUrl}`
    },
  },
  mounted() {
    this.getStoreList()

    this.getStatisticsList()
  },
  methods: {
    storeChange(e) {
      let storeName
      if (e) {
        storeName = this.storeList.filter((item) => {
          return item.id == e
        })[0].storeName
      } else {
        storeName = ''
      }
      this.queryParam.storeName = storeName

      this.searchQuery()
    },
    clickInfo(value) {
      console.log('value', value)
    },
    //获取所有门店列表
    async getStoreList() {
      // let res = await getAction('hc/hcMerchant/list', { pageNo: 1, pageSize: -1 })
      let res = await getAction('hc/hcMerchant/merchantList', { pageNo: 1, pageSize: -1 })
      console.log('res', res)
      this.storeList = res.result.records
    },

    // 复制
    handleCopy(record) {
      this.$refs.modalFormCopyThis.title = '复制'
      let obj = {
        "loginAccount": "",       // 新商户的登陆账号
        "merchantId": record.id,  // 被复制的商户的id
        "merchantName": ""        // 新商户的店名
      }
      this.$refs.modalFormCopyThis.edit(obj)
      this.$refs.modalFormCopyThis.disableSubmit = false
    },

    searchQuery() {
      this.loadData(1)
      this.getStatisticsList()
      // 点击查询清空列表选中行
      // https://gitee.com/jeecg/jeecg-boot/issues/I4KTU1
      this.selectedRowKeys = []
      this.selectionRows = []
    },
    getStatisticsList() {
      let that = this
      this.loading = true
      postAction('/hc/hcOrderMerchant/getStatisticsList', this.queryParam)
        .then((res) => {
          if (res.success) {
            let tempArr = []
            res.result.forEach((item, index) => {
              if (item.type == 'merchant' || item.type == 'merchantOrder') {
                tempArr.push(item)
              }
            })
            this.dataSourse = tempArr
            console.log('this.dataSource', this.dataSourse)
          } else {
            that.$message.warning(res.message)
          }
        })
        .finally(() => {
          that.loading = false
        })
    },

    editStateBatch(businessState) {
      let that = this

      this.$confirm({
        title: '',
        content: '是否确定把选中数据的营业状态改为' + (businessState == 0 ? '营业' : '打烊') + '?',
        onOk: function () {
          that.loading = true
          postAction('/hc/hcMerchant/editStateBatch', {
            selections: that.selectedRowKeys.join(','),
            businessState: businessState,
          })
            .then((res) => {
              if (res.success) {
                that.loadData()
                that.onClearSelected()
                that.$message.success(res.message)
              } else {
                that.$message.warning(res.message)
              }
            })
            .finally(() => {
              that.loading = false
            })
        },
      })
    },
    getTokenById(record) {
      let that = this

      getAction('/hc/hcMerchant/getTokenById', { id: record.id }).then((res) => {
        if (res.success) {
          window.open('https://merchant.yongshantuan.cn/#/pages/login/login?code=' + res.result.token, '_blank')
        } else {
          that.$message.warning(res.message)
        }
      })
    },
    stateEdit(record, index) {
      let that = this
      this.$set(this.dataSource[index], 'stateLoading', true)
      let state = record.businessState == '营业' ? 2 : 0
      postAction('/hc/hcMerchant/editState', { id: record.id, businessState: state })
        .then((res) => {
          if (res.success) {
            that.$message.success(res.message)
            that.loadData()
          } else {
            that.$message.warning(res.message)
          }
        })
        .finally(() => {
          this.$set(this.dataSource[index], 'stateLoading', false)
        })
    },
    initDictConfig() {},
    getSuperFieldList() {
      let fieldList = []
      fieldList.push({ type: 'string', value: 'logo', text: '门店LOGO' })
      fieldList.push({ type: 'string', value: 'storeDescription', text: '门店描述' })
      fieldList.push({ type: 'string', value: 'storeName', text: '门店名称' })
      fieldList.push({ type: 'string', value: 'storeUnitPrice', text: '门店菜品合作单价' })
      fieldList.push({ type: 'string', value: 'customPriceFlag', text: '开启自定义价格' })
      fieldList.push({ type: 'string', value: 'businessHoursBegin', text: '门店开始营业时间' })
      fieldList.push({ type: 'string', value: 'businessHoursEnd', text: '门店结束营业时间' })
      fieldList.push({ type: 'string', value: 'qualifications', text: '门店资质' })
      fieldList.push({ type: 'string', value: 'loginAccount', text: '门店登录账号' })
      fieldList.push({ type: 'number', value: 'packagingScore', text: '包装评分' })
      fieldList.push({ type: 'number', value: 'componentScore', text: '分量评分' })
      fieldList.push({ type: 'number', value: 'flavorScore', text: '口味评分' })
      fieldList.push({ type: 'int', value: 'sort', text: '排序' })
      this.superFieldList = fieldList
    },
  },
}
</script>
<style scoped>
@import '~@assets/less/common.less';
</style>